﻿using System;
using System.Collections.Generic;
using System.Linq;
using GeometricAlg.Model;
using GeometricAlg.Model.Polygon;
using GeometryLibrary.Algorithms;

namespace GeometryLibrary.Models
{
    public class Polygon2d
    {
        public List<Point2d> Vertices { get; private set; }

        public Polygon2d(List<Point2d> vertices)
        {
            if (vertices == null || vertices.Count < 3)
            {
                throw new ArgumentException("Polygon must have at least 3 vertices.");
            }

            Vertices = vertices;
        }

        /// <summary>  
        /// 计算多边形的面积。  
        /// </summary>  
        /// <returns>多边形的面积。</returns>  
        public double CalculateArea()
        {
            double area = 0;
            int j = Vertices.Count - 1;
            for (int i = 0; i < Vertices.Count; i++)
            {
                area += (Vertices[j].X + Vertices[i].X) * (Vertices[j].Y - Vertices[i].Y);
                j = i;
            }
            return Math.Abs(area / 2.0);
        }

        /// <summary>  
        /// 判断给定的点是否位于多边形内部。  
        /// </summary>  
        /// <param name="point">要判断的点。</param>  
        /// <returns>如果点在多边形内部，则返回 true；否则返回 false。</returns>  
        public bool ContainsPoint(Point2d point)
        {
            return PointInPolygonDetection.IsPointInsidePolygon(point, this);
        }

        /// <summary>  
        /// 获取多边形的边界框（最小外接矩形）。  
        /// </summary>  
        /// <returns>包含多边形所有顶点的最小矩形。</returns>  
        public Rectangle2d GetBoundingBox()
        {
            double minX = Vertices.Min(v => v.X);
            double minY = Vertices.Min(v => v.Y);
            double maxX = Vertices.Max(v => v.X);
            double maxY = Vertices.Max(v => v.Y);

            return new Rectangle2d(new Point2d(minX, minY), new Point2d(maxX, maxY));
        }

        // 可以添加其他多边形特有的方法，如计算周长、判断点是否在多边形的边上等。  
    }
}